package com.cl.edu.web.teacher;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.RandomStringUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;

import com.cl.common.util.Num62;
import com.cl.common.util.StringUtil;
import com.cl.common.util.UploadUtils;
import com.cl.core.web.struts2.Struts2Utils;
import com.cl.edu.entity.Teacher;
import com.cl.edu.entityVO.Photo;
import com.cl.edu.service.teacher.TeacherManager;
import com.opensymphony.xwork2.ActionSupport;

/**
 * 教员图片操作
 * 
 * @author Administrator
 * 
 */
@Results({ @Result(name = "success", location = "tc_photomanage.jsp") })
public class PhotoAction extends ActionSupport {

	@Autowired
	private TeacherManager teacherManager;
	
	private Teacher teacher;
	private Long id;
	 
	private File photo; // 上传的文件
	private String photoFileName; // 上传的文件名称
	private String photoContentType; // 上传的文件类型
	private String photoName; // 用户自定义的照片名

	private String savePath = File.separator+"upload"+File.separator+"teachers";

	private List<Photo> photosList = new ArrayList<Photo>();		//照片列表
	/**
	 * 进入页面时查询已上传图片列表
	 */
	public String execute() throws Exception {
		teacherManager.evict(teacher);
		teacher = teacherManager.getTeacher(id);
		String photos = teacher.getPhotos();
		if(StringUtil.isNotEmpty(photos)){
			String[] urls = photos.split("@@");
			for(String url:urls){
				String[] temp = url.split("@");
				Photo photo = new Photo();
				photo.setName(temp[0]);
				photo.setDesc(temp[1]);
				photosList.add(photo);
			}
		}
		
		return "success";
	}

	/**
	 * 上传图片
	 * @return
	 * @throws Exception
	 */
	public String upload() throws Exception {
		// 获取扩展名
		String ext = UploadUtils.getExtension(photoFileName);
		if (!"gif".equals(ext) && !"jpg".equals(ext) && !"png".equals(ext)) {
			addActionMessage("照片扩展名不符合要求!");
			return execute();
		}
		long size = photo.length();
		if (size > 1024 * 1024 * 512) {
			addActionMessage("照片大小不能大于512K!");
			return execute();
		}
		// 重命名文件
		String newFileName = RandomStringUtils.random(8, Num62.N36_CHARS) + "." + ext;
		String fullPath = getSavePath() + File.separator+id+File.separator+newFileName;
		String parentFolder = UploadUtils.getParentFolder(fullPath);
		try {
			//存入物理文件
			File file = new File(parentFolder);
			UploadUtils.checkDirAndCreate(file);
			FileOutputStream fos = new FileOutputStream(fullPath);
			FileInputStream fis = new FileInputStream(getPhoto());
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = fis.read(buffer)) > 0) {
				fos.write(buffer, 0, len);
			}
			
			//存入数据库
			teacher = teacherManager.getTeacher(id);
			String photos = teacher.getPhotos();
			if(StringUtil.isEmpty(photos)){
				photos = "";
			}
			photos+=newFileName+"@"+photoName+"@@";
			teacher.setPhotos(photos);
			teacherManager.updateTeacher(teacher);
			addActionMessage("上传成功!");
			
		} catch (Exception e) {
			addActionMessage("上传失败!");
			e.printStackTrace();
		}
		return execute();
	}
	
	/**
	 * 设置头像
	 * @return
	 * @throws Exception
	 */
	public String set() throws Exception {
		teacher = teacherManager.getTeacher(id);
		String name = Struts2Utils.getParameter("name");
		teacher.setPhoto(name);
		teacherManager.updateTeacher(teacher);
		Struts2Utils.getSession().setAttribute("teacher",teacher);//重新更新信息
		addActionMessage("设置头像成功!");
		return execute();
	}
	
	
	/**
	 * 删除图片
	 * @return
	 * @throws Exception
	 */
	public String del() throws Exception {
		teacher = teacherManager.getTeacher(id);
		String name = Struts2Utils.getParameter("name");
		File file = new File(getSavePath() + File.separator+id+File.separator+name);
		if(file.exists()){ //如果存在则删除文件
			file.delete();
		}
		String photo   = teacher.getPhoto();
		String weekStarPhoto = teacher.getWeekStarPhoto();
		if(name.equals(photo)){ //如删除的是头像，则头像为空
			teacher.setPhoto(null);
			Struts2Utils.getSession().setAttribute("teacher",teacher);//重新更新信息
		}
		if(name.equals(weekStarPhoto)){//如与一周之星图像设置相同，则清空一周之星图像
			teacher.setWeekStarPhoto(null);
			teacher.setIsWeekStar(0);//清除一周之星的显示
		}
		String  photos = teacher.getPhotos();
		teacher.setPhotos(photos.replaceAll(name+"@.*?@@", ""));
		if(StringUtil.isEmpty(teacher.getPhotos())){
			teacher.setPhotos(null);
		}
		teacherManager.updateTeacher(teacher);
		addActionMessage("删除成功!");
		return execute();
	}

	public File getPhoto() {
		return photo;
	}

	public void setPhoto(File photo) {
		this.photo = photo;
	}

	public String getPhotoFileName() {
		return photoFileName;
	}

	public void setPhotoFileName(String photoFileName) {
		this.photoFileName = photoFileName;
	}

	public String getPhotoContentType() {
		return photoContentType;
	}

	public void setPhotoContentType(String photoContentType) {
		this.photoContentType = photoContentType;
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getPhotoName() {
		return photoName;
	}

	public void setPhotoName(String photoName) {
		this.photoName = photoName;
	}

	public String getSavePath() {
		return ServletActionContext.getRequest().getRealPath(savePath);
	}

	public void setSavePath(String savePath) {
		this.savePath = savePath;
	}

	public Teacher getTeacher() {
		return teacher;
	}

	public void setTeacher(Teacher teacher) {
		this.teacher = teacher;
	}

	public List<Photo> getPhotosList() {
		return photosList;
	}

	public void setPhotosList(List<Photo> photosList) {
		this.photosList = photosList;
	}
}
